/**
 *
 *  LoginFilter.cc
 *
 */

#include "LoginFilter.h"

using namespace drogon;

void LoginFilter::doFilter(const HttpRequestPtr& req,
                           FilterCallback&&      fcb,
                           FilterChainCallback&& fccb)
{
    auto jsonPtr = req->jsonObject();
    if (!jsonPtr) {
        Json::Value ret;
        ret["error"] = "No json object is found in the request";
        auto resp    = HttpResponse::newHttpJsonResponse(ret);
        resp->setStatusCode(k400BadRequest);
        fcb(resp);
        return;
    }

    if (!jsonPtr->isMember("token") || !jsonPtr->isMember("user_id")) {
        Json::Value ret;
        ret["error"] = "请求格式错误!";
        auto resp    = HttpResponse::newHttpJsonResponse(ret);
        resp->setStatusCode(k400BadRequest);
        fcb(resp);
        return;
    }

    auto userId = (*jsonPtr)["user_id"].asString();
    auto token  = (*jsonPtr)["token"].asString();

    auto redisClientPtr = getRedisClient();

    redisClientPtr->execCommandAsync(
        [fcb, fccb, userId, token](const drogon::nosql::RedisResult& r) {
            Json::Value ret;
            do {
                if (r.type() != RedisResultType::kString) {
                    ret["error"] = "验证信息过期!";
                    break;
                }

                if (r.asString().compare(userId) != 0) {
                    ret["error"] = "非法请求!";
                    break;
                }
                return fccb();
            } while (false);
            auto resp = HttpResponse::newHttpJsonResponse(ret);
            resp->setStatusCode(k400BadRequest);
            return fcb(resp);
        },
        [token, fcb](const std::exception& err) {
            LOG_ERROR << "redis error!!! " << err.what();
            auto res = drogon::HttpResponse::newHttpResponse();
            res->setStatusCode(k500InternalServerError);
            fcb(res);
            return;
        },
        "GET %s", token.c_str());
}
